package com.ochnas.volunteersignup.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.persistence.NoResultException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ochnas.volunteersignup.domain.User;
import com.ochnas.volunteersignup.service.UserService;
import com.ochnas.volunteersignup.ui.LoginFormHandler;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		HttpSession session = req.getSession();
		
		LoginFormHandler loginHandler = (LoginFormHandler)session.getAttribute("loginFormHandler");
		
		if (loginHandler == null) {
			resp.sendRedirect("Login.jsp");
			return;
		}
		
		if (!req.getParameterMap().keySet().contains("emailAddress") &&
				!req.getParameterMap().keySet().contains("password")){
			resp.sendRedirect("Login.jsp");
			return;			
		}
		String emailAddress = (String) req.getParameter("emailAddress");
		String password = (String) req.getParameter("password");
		
		loginHandler.setEmailAddress(emailAddress);
		loginHandler.setPassword(password);
		if (loginHandler.validate()) {

			User user = loginHandler.login();
			if (user != null) { 
			PrintWriter out = resp.getWriter();
		
			String output = "<html>"
			+"<body>"
				+"<table>"
					+"<tr>"
						+"<td>"
							+"Entered email:"
						+"</td>"
						+"<td>"
							+(emailAddress == null ? "NULL" : emailAddress)
						+"</td>"
					+"</tr>"
					+"<tr>"
						+"<td>"
							+"Entered password:"
						+"</td>"
						+"<td>"
						+(password == null ? "NULL" : password)
						+"</td>"
					+"</tr>"
				+"</table>"
			+"</body>"
			+"</html>";
			
			out.println(output);
			} else {
				resp.sendRedirect("Login.jsp");
			}
		} else {
			resp.sendRedirect("Login.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
